#pragma once

#include <vld.h>
#include "templatevector.h"

#define CANNOT_OPEN_FILE 22

class FileParser
{
private:
	FILE * pFile;

public:

	//Prints the entire file to a vector<char*>
	int printFileToVector(TemplateVector<char*> & a_data, char* a_source)
	{
		fopen_s(&pFile,a_source,"r");

		if(pFile == NULL)
			return CANNOT_OPEN_FILE;
		char temp;
		char * newLine;
		newLine = new char[100];
		ZeroMemory(newLine,100);

		do {
			temp = fgetc (pFile);
			if(temp == '\n')
			{
				a_data.add(newLine);
				newLine = new char[128];
				ZeroMemory(newLine,128);
			}
			else if(temp == EOF)
				a_data.add(newLine);
			else
			{
				char temp[128];
				sprintf_s(temp,"%s%c",newLine,temp);
				strcpy_s(newLine,128,temp);
			}

			if(temp == EOF)
				delete newLine;

		} while (temp != EOF);

		if(pFile != NULL)
			fclose(pFile);
	}

	//Prints only what comes after a_symbol until a \n to a vector
	int printFileToVector(TemplateVector<char*> & a_data, char a_symbol, char* a_source)
	{
		auto error = fopen_s(&pFile,a_source,"r");
		if(error != NULL)
			return error;

		char temp;
		char * line = 0;
		char * newLine = 0;
		newLine = new char[128];
		ZeroMemory(newLine,128);

		do
		{
			temp = fgetc (pFile);

			if(temp == '*')
			{
				while(temp != '\n' && temp != EOF)
				{
					temp = fgetc (pFile);
				}
			}

			if(temp == a_symbol)
			{
				temp = fgetc (pFile);
				while(temp != '\n' && temp != EOF)
				{
					char tempLine[128]; ZeroMemory(&tempLine,128);
					sprintf_s(tempLine,"%s%c",newLine,temp);
					strcpy_s(newLine,128,tempLine);
					temp = fgetc (pFile);
				}
				if((temp == '\n' || temp == EOF) && newLine[0] != EOF)
				{
					a_data.add(newLine);
					newLine = new char[128];
					ZeroMemory(newLine,128);
				}
			}
		} while (temp != EOF);

		if(temp == EOF)
			delete newLine;

		if(pFile != NULL)
			fclose(pFile);

		return 0;
	}

	//Prints out everything that isn't included into the string
	int printFileToVector(TemplateVector<char*> & a_out, char* a_symbols, char* a_source)
	{
		int counter = 0;
		int secondCounter = 0;
		printFileToVector(a_out, a_source);
		char symbol = a_symbols[counter];
		while(symbol !='\0')
		{
			for (int i = a_out.size()-1; i >= 0; i--)
			{
				if((a_out[i][0] == symbol) || (a_out[i][0] == '\n') || (a_out[i][0] == 0))
				{
					delete a_out[i];
					a_out.remove(i);
				}
				secondCounter ++;
			}
			symbol = a_symbols[++counter];
		}
		return 0;
	}
};